package com.wondertek.mist.plugins;


import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.AlertDialog;
import android.content.DialogInterface;


public class SelectWidgetPlugin extends CordovaPlugin {

    static String TAG = "SelectWidgetPlugin";


    
    
    /**
     * Constructor.
     */
    public SelectWidgetPlugin() {
    }

   
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
            
    	//args:['title',0,['aa','bb','cc']]
    	if("show".equalsIgnoreCase(action)){
    	
    		final String title=args.getString(0);
    		final int selectedIndex=args.getInt(1);
    		
    		
    		JSONArray array=args.getJSONArray(2);
    		
    		final CharSequence[] items = new CharSequence[array.length()];
    		for(int i=0;i<array.length();i++){
    			items[i]=array.getString(i);
    		}
    		
    		
    		final CallbackContext callback=callbackContext;
    		
            Runnable runnable = new Runnable() {
        	
                public void run() {
        	
                	
                	
    		    	AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getActivity());
    		    	builder.setTitle( title );
    				
    		    	builder.setSingleChoiceItems(items, selectedIndex, new DialogInterface.OnClickListener() {
    		    	    public void onClick(DialogInterface dialog, int index) {
    		    	    	dialog.dismiss();
    						
    		    	    	callback.sendPluginResult(new PluginResult(PluginResult.Status.OK,index));                        
    		    	    }
    		    	});
				    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int which) {
								dialog.dismiss();
				            }
					});
    		    	AlertDialog dialog = builder.create();
    		    	
    		    	dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
    		    	dialog.show();    
                }
            };
            this.cordova.getActivity().runOnUiThread(runnable);
    		
    	}
        return true;
    }

  
    
}
